<template>
  <div>
    <div v-if="!showEditor" class="editor-placeholder" @click="showEditor = true" v-html="value" />
    <div v-else> <vue-ueditor-wrap ref="editor" v-model="content" :config="config" :init="init" @beforeInit="beforeInit" /></div>
    <!-- 素材选择框 -->
    <el-dialog title="选择素材" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <select-material :attach-id.sync="material" @autoChecked="autoChecked" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="insertMaterial">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap';
import SelectMaterial from '@/pages/material/SelectMaterial/index.vue';
export default {
  components: {
    VueUeditorWrap,
    SelectMaterial
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    format: {
      type: String,
      default: 'primary',
      validator(val) {
        return ['primary'].indexOf(val) !== -1;
      }
    }
  },
  data() {
    const bars = {
      'primary': [
        // 'source',
        'fullscreen',
        '|',
        'undo',
        'redo',
        '|',
        'bold',
        'italic',
        'underline',
        'fontborder',
        'strikethrough',
        'superscript',
        'subscript',
        'removeformat',
        'formatmatch',
        'autotypeset',
        'blockquote',
        'pasteplain',
        '|',
        'forecolor',
        'backcolor',
        'insertorderedlist',
        'insertunorderedlist',
        // 'selectall',
        // 'cleardoc',
        '|',
        'rowspacingtop',
        'rowspacingbottom',
        'lineheight',
        '|',
        'customstyle',
        'paragraph',
        'fontfamily',
        'fontsize',
        '|',
        'directionalityltr',
        'directionalityrtl',
        'indent',
        '|',
        'justifyleft',
        'justifycenter',
        'justifyright',
        'justifyjustify',
        '|',
        'touppercase',
        'tolowercase',
        '|',
        'link',
        'unlink',
        'anchor',
        // '|',
        // 'imagenone',
        // 'imageleft',
        // 'imageright',
        // 'imagecenter',
        '|',
        // 'simpleupload',
        // 'insertimage',
        'emotion',
        'scrawl',
        // 'insertvideo',
        // 'music',
        // 'attachment',
        // 'map',
        // 'gmap',
        // 'insertframe',
        'insertcode',
        'pagebreak',
        'template',
        // 'background',
        '|',
        'horizontal',
        'date',
        'time',
        'spechars',
        // 'snapscreen',
        // 'wordimage',
        // '|',
        // 'inserttable',
        // 'deletetable',
        // 'insertparagraphbeforetable',
        // 'insertrow',
        // 'deleterow',
        // 'insertcol',
        // 'deletecol',
        // 'mergecells',
        // 'mergeright',
        // 'mergedown',
        // 'splittocells',
        // 'splittorows',
        // 'splittocols',
        // 'charts',
        '|',
        'print',
        'preview',
        'searchreplace',
        'drafts',
        'kityformula',
        'help'
      ]
    }
    return {
      // 是否显示弹出层
      dialogVisible: false,
      material: {},
      // 是否显示编辑器
      showEditor: false,
      // 当前编辑器
      editor: null,
      // 编辑器内容
      content: '',
      // 配置编辑器
      config: {
        UEDITOR_HOME_URL: '/UEditor/',
        autoHeightEnabled: false,
        initialFrameWidth: 900,
        initialFrameHeight: 300,
        wordCount: false,
        toolbars: [[...bars[this.format]]],
        serverUrl: ''
      }
    };
  },
  watch: {
    value(val) {
      // 外部内容发生变化时，将新值赋予编辑器
      if (val && val !== this.content) {
        this.content = this.value;
      }
    },
    content(val) {
      if (val !== this.value) {
        // 编辑器内容发生变化时，告知外部，实现 v-model 双向监听效果
        this.$emit('input', val);
      }
    }
  },
  mounted() {
    this.content = this.value;
  },
  methods: {
    beforeInit() {
      require('/public/UEditor/third-party/kityformula-plugin/addKityFormulaDialog.js');
      require('/public/UEditor/third-party/kityformula-plugin/defaultFilterFix.js');
      require('/public/UEditor/third-party/kityformula-plugin/getKfContent.js');
    },
    init() {
      this.$refs.editor.registerButton({
        name: '素材',
        icon: '/static/images/sucai.png',
        tip: '选择素材',
        handler: (editor, name) => {
          this.dialogVisible = true;
          this.editor = editor;
          // editor.execCommand('inserthtml', '<p><img src="https://1301675900.vod2.myqcloud.com/df194f02vodcq1301675900/98c188a55285890807320296222/f0.png" /></p>');
        }
      })
    },
    // 自动选中,当素材为上传时,自动选中上传的素材
    autoChecked() {
      this.insertMaterial();
    },
    // 插入素材
    insertMaterial() {
      const { type, attachId } = this.material;
      this.$http.get('/attach/' + attachId + '/view/url', {}, ({ data }) => {
        const url = data.url;
        switch (type) {
          case 'image':
            // 图片
            this.editor.execCommand('inserthtml', '<img src="' + url + '" class="material-image" />');
            break;
          case 'audio':
            // 音频
            this.editor.execCommand('inserthtml', '<audio controls src="' + url + '" class="material-audio">暂不支持音频预览</audio> ');
            break;
          case 'video':
            // 视频
            this.editor.execCommand('inserthtml', '<video controls style="width:480px;height:auto;" src="' + url + '" class="material-video">暂不支持视频预览</video> ');
            break;
        }
        this.dialogVisible = false;
      }, _ => {})
    },
	// 清空输入
    clearContent() {
      this.content = '';
    }
  }
};
</script>

<style lang="scss">
.editor-placeholder{
  min-height: 28px;
  border: 1px solid #d5d8de;
}
.edui-default .edui-toolbar {
  .edui-box {
    line-height: initial;
  }
  .edui-for-fullscreen {
    float: none !important;
  }
}
</style>
